<template>
  <view class="payment-container">
    <!-- 磨砂玻璃背景 -->
    <view class="background-blur"></view>
    
    <!-- 头部区域 -->
    <view class="header">
      <view class="payment-amount-card">
        <view class="amount-label">待支付金额</view>
        <price-format
          v-if="amount !== undefined && amount !== null"
          class="amount-display"
          :subscript-size="40"
          :first-size="72"
          :second-size="50"
          :price="amount"
          :weight="600"
          text-color="#111111"
        />
        <view v-else class="amount-placeholder">
          <text>¥ ---.--</text>
        </view>
        
        <!-- 倒计时区域 -->
        <view class="countdown-container" v-if="timeout > 0">
          <view class="countdown-icon">
            <u-icon name="clock-fill" size="24" color="#FF3B30"></u-icon>
          </view>
          <text class="countdown-text">支付剩余</text>
          <u-count-down
            class="countdown-timer"
            :timestamp="timeout"
            :show-days="false"
            :show-hours="false"
            separator-color="#FF3B30"
            color="#FF3B30"
            bg-color="rgba(255, 59, 48, 0.1)"
            :font-size="24"
            separator="："
            :show-border="true"
            border-color="rgba(255, 59, 48, 0.2)"
            padding="4rpx 8rpx"
            border-radius="6rpx"
          />
        </view>
      </view>
    </view>
    
    <!-- 主体内容区域 - 自动延伸 -->
    <view class="content">
      <view class="section-title">
        <view class="title-dot"></view>
        <text>选择支付方式</text>
      </view>
      
      <!-- 支付方式列表 -->
      <view class="payment-methods" v-if="paywayList && paywayList.length > 0">
        <u-radio-group v-model="payway" class="methods-container">
          <view
            class="payment-method-item"
            v-for="(item, index) in paywayList"
            :key="item.id || index"
            :class="{'active': payway === item.pay_way}"
            @click="changePayway(item.pay_way)"
          >
            <view class="method-icon-container">
              <u-image
                :src="item.image"
                width="56"
                height="56"
                mode="scaleToFill"
                border-radius="16"
              />
              <view class="method-check" v-if="payway === item.pay_way">
                <u-icon name="checkmark" color="#FFFFFF" size="16"></u-icon>
              </view>
            </view>
            
            <view class="method-info">
              <text class="method-name">{{ item.name }}</text>
              <text class="method-desc">{{ item.extra || '' }}</text>
            </view>
          </view>
        </u-radio-group>
      </view>
      
      <!-- 无支付方式提示 -->
      <view class="empty-methods" v-else>
        <u-icon name="info-circle" size="60" color="#CCCCCC"></u-icon>
        <text>暂无可用支付方式</text>
      </view>
      
      <!-- 扩展信息区域 -->
      <view class="payment-info">
        <view class="info-item">
          <u-icon name="shield-check" size="28" color="#07C160"></u-icon>
          <text>支付安全保障</text>
        </view>
        <view class="info-item">
          <u-icon name="red-packet" size="28" color="#FF9500"></u-icon>
          <text>部分银行卡支付可享优惠</text>
        </view>
      </view>
      
      <!-- 底部间隔 - 为底部固定按钮留出空间 -->
      <view class="content-bottom-space"></view>
    </view>
    
    <!-- 底部支付按钮 - 固定在底部 -->
    <view class="footer">
      <button 
        class="pay-button" 
        :class="{'disabled': loadingPay || !(paywayList && paywayList.length > 0)}" 
        @tap="handlePrepay"
      >
        <view class="button-inner">
          <u-loading mode="circle" :show="loadingPay" color="#FFFFFF" size="28" />
          <text v-show="!loadingPay">立即支付</text>
        </view>
        <view class="button-shine"></view>
      </button>
      
      <view class="footer-info">
        <text>支付即表示同意</text>
        <text class="link">《支付服务条款》</text>
      </view>
    </view>
    
    <!-- 骨架屏 -->
    <u-skeleton 
      :loading="loadingSkeleton" 
      :animation="true" 
      bgColor="rgba(255,255,255,0.8)" 
    />
  </view>
</template>

<script>
// 保留原有脚本逻辑，这里不改变任何功能
/**
 * @description 支付页面
 * @query {String} from 订单来源: order-商品订单; recharge-充值订单;
 * @query {Number} order_id	订单ID
 */
import { prepay, getPayway } from '@/api/app'
import { wxpay, alipay, sand } from '@/utils/pay'
import { getPayResult, changePayWay } from '@/api/order'
import {client} from '@/utils/tools'


export default {
    name: 'Payment',

    data() {
        return {
            from: '', // 订单来源
            order_id: '', // 订单ID
            amount: 0, // 支付金额
            timeout: 0, // 倒计时间戳
            payway: '', // 支付方式
            paywayList: [], // 支付方式列表
            showAgain: false,
            loadingSkeleton: true, // 骨架屏Loading
            loadingPay: false, // 支付处理中Loading
            result: '', // 支付结果
            second_buy: 0,  //是否是云购  0：否  1：是
			
        }
    },

    methods: {
        // 更改支付方式
        changePayway(value) {
            this.$set(this, 'payway', value)
            changePayWay({
                from: this.from,
                order_id: this.order_id,
                pay_way: this.payway
            }).then((res) => {
                if (res.code != 1) throw new Error(res.msg)
                return res.data
            })
            .then((data) => {
                this.loadingSkeleton = false
                this.amount = data.order_amount
            })
            .catch((err) => {
                throw new Error(err)
            })
        },

        // 初始化页面数据
        initPageData() {
            // 获取支付方式
            //判断是否是云购活动进来的商品  this.second_buy 1：是  0：否
          
            getPayway({
                from: this.from,
                order_id: this.order_id,
                second_buy: this.second_buy,
            })
            .then((res) => {
                if (res.code != 1) throw new Error(res.msg)
                return res.data
            })
            .then((data) => {
                this.loadingSkeleton = false
                this.amount = data.order_amount
                this.paywayList = data.pay_way
                this.payway = this.paywayList[0]?.pay_way
                // 倒计时
                const startTimestamp = new Date().getTime()
                const endTimestamp = data.cancel_time
                this.timeout = endTimestamp - startTimestamp / 1000
            })
            .catch((err) => {
                throw new Error(err)
            })
        },

        // 预支付处理
        handlePrepay() {
            if (this.loadingPay || !this.paywayList.length) return
            this.loadingPay = true;
            console.log(this.second_buy);   //判断是否是云购活动进来的商品
            let obj = {
              from: this.from,
              order_id: this.order_id,
              pay_way: this.payway,
              client: client,
            }
            if (this.second_buy == 1) {   //如果是云购活动进来的商品，需要传参second_buy 1：是  0：否
              obj.second_buy = 1;
            } else {
              delete obj.second_buy;
            }
            console.log(obj);
            prepay(obj)
            .then(({ code, data, pay_way }) => {
              console.log('code:' + code);
                switch (code) {
                    case 1:
                        this.handleWechatPay(data)
                        break
                    case 10001:
                        this.handleAlipayPay(data, pay_way)
                        break
                    case 20001:
                        this.handleWalletPay()
                        break
                    case 30001:
                        this.handleSandPay(data, pay_way)
                        break
                    case 11:
                        this.handleUnifiedpay(data)   //通联支付通道微信H5收银台
                        break
                    case 21:
                        // console.log('通联支付通道');
                        // console.log(data);
                        this.$appJumpMiniPro(data.path);
                        // this.handleMiniProgramPay(data)   //通联支付通道(通联小程序支付收银台)
                        break
                    case 31:
                        console.log('汇付支付通道');
                        console.log(data);
                        // this.$appJumpMiniPro(data.data.payData);
                        // this.handleMiniProgramPay(data)   //汇付支付通道微信
                        // #ifdef APP-PLUS
                        console.log('数据转化');
                        let tempObj = JSON.parse(data.data.payData);
                        let tempObj2 = JSON.parse(tempObj.miniapp_data);
                        console.log(typeof tempObj2);
                        let ghId = tempObj2.gh_id;
                        let url = tempObj2.path + '?p=' + tempObj.pre_order_id + '&s=app';
                        this.$appJumpMiniPro(ghId, url);
                        // #endif
                        // #ifdef H5
                        location.href = data.data.payData;
                        // #endif
                        break
                    case 12:
                        console.log('通联支付通道');
                        console.log(data);
                        this.handleUnifiedAlipay(data)   //通联支付通道支付宝H5收银台
                        break

                }
            })
            .catch((err) => {})
            .finally(() => {
                setTimeout(() => {
                    this.loadingPay = false
                }, 500)
            })
        },

        // 微信支付
        handleWechatPay(data) {
            wxpay(data)
                .then((res) => {
                    console.log(res)
                    this.handPayResult(res)
                })
                .catch((err) => {
                    console.log(err)
                })
        },

        //通联支付H5收银台
        handleUnifiedpay(data) {
          console.log(data);
          window.location.href = data;
          console.log('通联支付通道');
        },
        //通联支付小程序收银台
        // handleMiniProgramPay(data) {
        //   console.log(data);
        //   wx.miniapp.launchMiniProgram({
        //     userName: 'gh_e64a1a89a0ad', //小程序原始ID
        //     path: data.path,
        //     miniprogramType: 2, //0 release ，1 test, 2 preview
        //     success: (res) => {
        //         wx.showModal({
        //             content: res.data,
        //         })
        //         console.log('get wx phonenumber success:', res)
        //     }
        //   })
        // },
        //通联支付支付宝H5收银台
        handleUnifiedAlipay(data) {
          console.log(data);
          console.log('通联支付宝支付通道');
          let url = `alipays://platformapi/startapp?appId=20000067&ur1=\(data)`;
          window.location.href = url;
        },
        // 支付宝支付
        handleAlipayPay(data, pay_way) {
            console.log(pay_way)
            
            alipay(data, pay_way)        
            
                .then((res) => {
                    this.handPayResult(res)
                })
                .catch((err) => {
                    console.log(err)
                })
        },
        
        handleSandPay(data, pay_way) {            
            sand(data, pay_way)        
            
                .then((res) => {
                    this.handPayResult(res)
                })
                .catch((err) => {
                    console.log(err)
                })
        },

        // 钱包余额支付
        handleWalletPay() {
            console.log('支付成功')
            //余额支付成功
            this.handPayResult('success')
        },

        // 支付后处理
        handPayResult(result) {
            // 页面出栈
            //记录支付结果
            this.result = result
            // uni.navigateBack()
            this.$Router.back(1)
        }
    },

    onLoad() {
        const options = this.$Route.query
        console.log(options);
        const from = options?.from || 'trade'
        const order_id = options?.order_id
        const is_second_buy = options?.is_second_buy;  //判断是否是云购活动进来的商品
        console.log(is_second_buy);

        try {
            if (!from && !order_id) throw new Error('页面参数有误')
            this.from = from
            this.order_id = order_id
            this.second_buy = is_second_buy ? 1 : 0;
            console.log(this.second_buy);
            this.initPageData()
        } catch (err) {
            console.log(err)
            // uni.navigateBack()
            this.$Router.back()
        }
    },
    
    onShow() {
        if (this.showAgain) {
            getPayResult({
                from: this.from,
                order_id: this.order_id,
                id: this.order_id
            }).then(({ data }) => {
                if (data.pay_status) {
                    console.log(456789)
                    this.result = 'success'
                } else {
                    this.result = 'fail'
                }
                this.$Router.back(1)
            })
        }
    },
    
    onHide() {
        this.showAgain = true
    },

    onUnload() {
        switch (this.result) {
            case 'success':
                uni.$emit('payment', {
                    result: true,
                    order_id: this.order_id,
                    from: this.from
                })
                break
            case 'fail':
            default:
                uni.$emit('payment', {
                    result: false,
                    order_id: this.order_id,
                    from: this.from
                })
        }
    }
}
</script>

<style lang="scss">
page {
  background-color: #f8f9fa;
  height: auto;
  min-height: 100%;
}

/* 主容器样式 */
.payment-container {
  position: relative;
  min-height: 100vh;
  padding-bottom: 220rpx; /* 为固定底部留出空间 */
  
  /* 磨砂玻璃背景 */
  .background-blur {
    position: absolute;
    top: -50%;
    right: -20%;
    width: 120%;
    height: 60%;
    background: linear-gradient(135deg, #FF3B30 0%, #FF9500 100%);
    border-radius: 0 0 50% 60%;
    filter: blur(30px);
    opacity: 0.8;
    z-index: -1;
  }
  
  /* 头部区域 */
  .header {
    padding: 30rpx;
    margin-top: 40rpx;
    
    .payment-amount-card {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(20px);
      border-radius: 24rpx;
      padding: 40rpx;
      box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.08);
      position: relative;
      overflow: hidden;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 8rpx;
        background: linear-gradient(90deg, #FF3B30, #FF9500);
      }
      
      .amount-label {
        font-size: 28rpx;
        color: #888888;
        margin-bottom: 16rpx;
      }
      
      .amount-display {
        margin-bottom: 30rpx;
      }
      
      .amount-placeholder {
        font-size: 72rpx;
        font-weight: 600;
        color: #cccccc;
        margin-bottom: 30rpx;
      }
      
      .countdown-container {
        display: flex;
        align-items: center;
        background: rgba(255, 59, 48, 0.05);
        border-radius: 36rpx;
        padding: 12rpx 24rpx;
        width: fit-content;
        
        .countdown-icon {
          margin-right: 12rpx;
        }
        
        .countdown-text {
          font-size: 24rpx;
          color: #FF3B30;
          margin-right: 12rpx;
        }
        
        .countdown-timer {
          /* 样式将通过props传递 */
        }
      }
    }
  }
  
  /* 内容区域 */
  .content {
    margin: 30rpx;
    margin-top: 20rpx;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    border-radius: 24rpx;
    padding: 40rpx 30rpx;
    box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.05);
    position: relative;
    overflow: hidden;
    
    .section-title {
      display: flex;
      align-items: center;
      margin-bottom: 40rpx;
      
      .title-dot {
        width: 12rpx;
        height: 36rpx;
        background: #FF3B30;
        border-radius: 6rpx;
        margin-right: 16rpx;
      }
      
      text {
        font-size: 32rpx;
        font-weight: 600;
        color: #333333;
      }
    }
    
    /* 支付方式列表 */
    .payment-methods {
      .methods-container {
        display: flex;
        flex-direction: column;
      }
      
      .payment-method-item {
        display: flex;
        align-items: center;
        padding: 30rpx;
        margin-bottom: 24rpx;
        background: #FFFFFF;
        border-radius: 16rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
        position: relative;
        transition: all 0.3s ease;
        
        &.active {
          background: rgba(255, 59, 48, 0.05);
          border: 1px solid rgba(255, 59, 48, 0.2);
          transform: scale(1.02);
          box-shadow: 0 8rpx 24rpx rgba(255, 59, 48, 0.1);
        }
        
        .method-icon-container {
          position: relative;
          margin-right: 24rpx;
          
          .method-check {
            position: absolute;
            bottom: -6rpx;
            right: -6rpx;
            width: 32rpx;
            height: 32rpx;
            background: #FF3B30;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4rpx 8rpx rgba(255, 59, 48, 0.3);
          }
        }
        
        .method-info {
          flex: 1;
          
          .method-name {
            font-size: 30rpx;
            color: #333333;
            font-weight: 500;
            margin-bottom: 6rpx;
          }
          
          .method-desc {
            font-size: 24rpx;
            color: #999999;
          }
        }
      }
    }
    
    /* 无支付方式提示 */
    .empty-methods {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 80rpx 0;
      
      text {
        font-size: 28rpx;
        color: #999999;
        margin-top: 20rpx;
      }
    }
    
    /* 支付信息提示 */
    .payment-info {
      margin-top: 40rpx;
      padding-top: 30rpx;
      border-top: 1px dashed rgba(0, 0, 0, 0.08);
      
      .info-item {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
        
        text {
          font-size: 24rpx;
          color: #666666;
          margin-left: 10rpx;
        }
      }
    }
    
    /* 底部空间 - 为固定底部留出空间 */
    .content-bottom-space {
      height: 40rpx;
    }
  }
  
  /* 底部区域 - 固定在页面底部 */
  .footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 30rpx;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(20px);
    /* 修复底部安全距离 - 同时支持新旧iOS版本 */
    padding-bottom: calc(30rpx + constant(safe-area-inset-bottom)); /* iOS 11.0-11.2 */
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom)); /* iOS 11.2+ */
    z-index: 100;
    box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.05);
    
    .pay-button {
      position: relative;
      height: 98rpx;
      border-radius: 49rpx;
      background: linear-gradient(135deg, #FF3B30, #FF9500);
      box-shadow: 0 10rpx 30rpx rgba(255, 59, 48, 0.3);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 32rpx;
      color: #FFFFFF;
      font-weight: 600;
      overflow: hidden;
      border: none;
      
      &.disabled {
        opacity: 0.6;
        background: linear-gradient(135deg, #cccccc, #aaaaaa);
        box-shadow: none;
      }
      
      .button-inner {
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 2;
        
        text {
          margin-left: 10rpx;
        }
      }
      
      .button-shine {
        position: absolute;
        top: 0;
        left: -100%;
        width: 60%;
        height: 100%;
        background: linear-gradient(
          90deg, 
          rgba(255,255,255,0) 0%, 
          rgba(255,255,255,0.3) 50%, 
          rgba(255,255,255,0) 100%
        );
        transform: skewX(-25deg);
        animation: shine 3s infinite;
        z-index: 1;
      }
      
      &:active:not(.disabled) {
        transform: scale(0.98);
      }
    }
    
    .footer-info {
      text-align: center;
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #999999;
      
      .link {
        color: #FF3B30;
      }
    }
  }
}

/* 动画效果 */
@keyframes shine {
  0% {
    left: -100%;
  }
  20% {
    left: 100%;
  }
  100% {
    left: 100%;
  }
}
</style>